<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true">
          <el-form-item label="设备类型" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择设备类型" clearable>
              <el-option
                v-for="dict in sys_equip_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="被替换设备标签" prop="olabel">
            <el-input v-model="queryParams.olabel" placeholder="请输入被替换设备标签" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item label="替换设备标签" prop="nlabel">
            <el-input v-model="queryParams.nlabel" placeholder="请输入替换设备标签" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:changeRecord:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:changeRecord:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:changeRecord:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:changeRecord:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="changeRecordList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备类型" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="sys_equip_type" :value="scope.row.type"/>
          </template>
        </el-table-column>
        <el-table-column label="所属电站" align="center" prop="stationId" />
        <el-table-column label="所属用户" align="center" prop="userId" />
        <el-table-column label="所属用户邮箱" align="center" prop="email" />
        <el-table-column label="被替换设备标签" align="center" prop="olabel" />
        <el-table-column label="被替换设备序列号" align="center" prop="osn" />
        <el-table-column label="替换设备标签" align="center" prop="nlabel" />
        <el-table-column label="替换设备序列号" align="center" prop="nsn" />
        <el-table-column label="替换说明" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:changeRecord:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:changeRecord:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改设备替换对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="changeRecordFormRef" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="设备类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择设备类型">
            <el-option
                v-for="dict in sys_equip_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属电站" prop="stationId">
          <el-select  v-loadmore="loadMore" class="more-select" popper-class="more_select_dropdown" filterable remote :remote-method="remoteMethod" :loading="loading" v-model="form.stationId" @change="change">
              <el-option :key="item.id" :label="item.stationName" :value="item.id"  v-for="item in powerData">
                <span style="float: left; font-size: 13px">{{ item.stationName}}</span>
              </el-option>
              <!-- <template #prefix><el-icon><Search /></el-icon></template> -->
          </el-select>
        </el-form-item>
        <el-form-item label="被替换设备标签" prop="olabel">
          <el-input v-model="form.olabel" placeholder="请输入被替换设备标签" />
        </el-form-item>
        <el-form-item label="替换设备标签" prop="nlabel">
          <el-input v-model="form.nlabel" placeholder="请输入替换设备标签" />
        </el-form-item>
        <el-form-item label="替换说明" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ChangeRecord" lang="ts">
import { listChangeRecord, getChangeRecord, delChangeRecord, addChangeRecord, updateChangeRecord } from '@/api/system/changeRecord';
import { ChangeRecordVO, ChangeRecordQuery, ChangeRecordForm } from '@/api/system/changeRecord/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_equip_type } = toRefs<any>(proxy?.useDict('sys_equip_type'));

const changeRecordList = ref<ChangeRecordVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const changeRecordFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ChangeRecordForm = {
  type: undefined,
  stationId: undefined,
  olabel: undefined,
  nlabel: undefined,
  remark: undefined,
}
const data = reactive<PageData<ChangeRecordForm, ChangeRecordQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: undefined,
    olabel: undefined,
    nlabel: undefined,
    params: {
    }
  },
  rules: {
    type: [
      { required: true, message: "设备类型不能为空", trigger: "change" }
    ],
    stationId: [
      { required: true, message: "所属电站不能为空", trigger: "blur" }
    ],
    olabel: [
      { required: true, message: "被替换设备标签不能为空", trigger: "blur" }
    ],
    nlabel: [
      { required: true, message: "替换设备标签不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "替换说明不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询设备替换列表 */
const getList = async () => {
  loading.value = true;
  const res = await listChangeRecord(queryParams.value);
  changeRecordList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  changeRecordFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ChangeRecordVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加设备替换";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ChangeRecordVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getChangeRecord(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改设备替换";
}

/** 提交按钮 */
const submitForm = () => {
  changeRecordFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateChangeRecord(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addChangeRecord(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ChangeRecordVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除设备替换编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delChangeRecord(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/changeRecord/export', {
    ...queryParams.value
  }, `changeRecord_${new Date().getTime()}.xlsx`)
}

import { ComponentInternalInstance,Ref } from "vue";
import useStationStore from '@/store/modules/station'
import { getSimpleStationList } from '@/api/homeIndex';
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const stationStore = useStationStore();
const storedValue = sessionStorage.getItem('powerStationList');
const defaultValue = '[]';
const powerData = ref(storedValue !== undefined && storedValue !== null ? JSON.parse(storedValue) : JSON.parse(defaultValue));

const powerName =ref('');
const loadStatus =ref(true);//默认可加载，还有下一页
const router = useRouter();

// 分页
const queryData = reactive({
    page: 1, // 当前页码
    pagesize: 10, //每页条数
    total: 0, // 总数
  });
const loadMore = () => {
    getpowerData()
  };
  const dedupObjectArray = (arr, key) => {
    const seen = new Map();
    return arr.filter((item) => {
      const itemKey = item[key];
      return seen.has(itemKey) ? false : seen.set(itemKey, true);
    });
  };
  // 获取电站列表
 const getpowerData =  async () => {
    loading.value = true;
    let query = {
      searchValue: powerName.value,
      pageNum: queryData.page,
      pageSize: queryData.pagesize,
    };
    if(loadStatus.value){
      let res = await getSimpleStationList(query);
      powerData.value = powerData.value.concat(res.rows);
      powerData.value = dedupObjectArray(powerData.value,'id');
      queryData.total = res.total;
      if(queryData.pagesize*queryData.page>=res.total){
        loadStatus.value=false//不允许请求下一页了
      }else queryData.page++
    }
    loading.value = false;
    sessionStorage.setItem('powerStationList', JSON.stringify(powerData.value));
  };
  //远程搜索
  const remoteMethod= (query:string) =>  {
    powerName.value=query
    queryData.page=1
    loadStatus.value=true
    powerData.value=[]
    getpowerData()
  }
  onMounted(() => {
    getList();
    getpowerData();
    powerData.value = dedupObjectArray(powerData.value,'id');
  });
</script>
